package com.kingyea.mobilepolice.apimanage.requester.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.kingyea.mobilepolice.apimanage.log.OperateType;
import com.kingyea.mobilepolice.apimanage.log.OperationLogAnnotation;
import com.kingyea.mobilepolice.apimanage.provider.vo.ProviderVO;
import com.kingyea.mobilepolice.apimanage.requester.bean.Requester;
import com.kingyea.mobilepolice.apimanage.requester.service.RequesterService;
import com.kingyea.mobilepolice.apimanage.requester.vo.MonthlyRequesterCountVo;
import com.kingyea.mobilepolice.apimanage.requester.vo.RequesterVo;
import com.kingyea.mobilepolice.apimanage.sysvo.bean.AllCondition;
import com.kingyea.mobilepolice.apimanage.utils.page.PageInfo;
import com.kingyea.mobilepolice.system.Result;
import com.kingyea.mobilepolice.user.bean.User;
import com.kingyea.mobilepolice.user.client.UserServiceClient;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Mr.Lin
 * @version v1.0.0
 * @description Requester 控制层
 * @date Created in 2018-02-23 14:55:28
 */
@RequestMapping(value = "/requester")
@RestController
public class RequesterController {

    private static final Logger LOGGER = LoggerFactory.getLogger(RequesterController.class);

    @Autowired
    private RequesterService requesterService;
    @Autowired
    private UserServiceClient userServiceClient;

    /**
     * 条件查询
     *
     * @param map
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "根据搜索条件搜索服务方列表", notes = "", response = ProviderVO.class)
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = true, dataType = "Date")
            , @ApiImplicitParam(name = "endTime", value = "结束时间", required = true, dataType = "Date")
            , @ApiImplicitParam(name = "pageNum", value = "第几页", required = true, dataType = "int")
            , @ApiImplicitParam(name = "pageSize", value = "每页数据数量大小", required = true, dataType = "int")
            , @ApiImplicitParam(name = "keyword", value = " 关键字keyword，订单号和代理商名字 ", required = false, dataType = "Integer")
            , @ApiImplicitParam(name = "searchType", value = " 搜索类型（serialNo.请求者标识 requester.请求方名称 requestNetwork.请求方所属的网络类型 organizationId.管理单位机构代码 organization.管理单位名称 requestMac.请求者的mac地址 userId.注册用户） ", required = true, dataType = "String")
            // 以下参数一般用于适应关联页面列表里边的筛选
            , @ApiImplicitParam(name = "status", value = " 状态：1:注册未审核，2:变更未审核，3:审核通过，4:审核不通过 ", required = false, dataType = "Integer")
            , @ApiImplicitParam(name = "isDel", value = " 是否删除：0.否 1.是 ", required = false, dataType = "Integer")

    })
    @OperationLogAnnotation(operateName = "条件查询请求方列表", operateType = OperateType.SELECT, module = "requester")
    @RequestMapping(value = "/searchByCondition", method = RequestMethod.POST)
    public Object searchByCondition(@RequestBody Map<String, Object> map) throws Exception {
        if (map.containsKey("roleId")) {
            if (!"".equals(map.get("roleId")) && Integer.parseInt(map.get("roleId").toString()) == 0) {
                map.put("idAdmin", null);
            } else {
                map.put("isAdmin", userServiceClient.getCurrentUserInfo().getData().getUserId());
            }
        }
        if (map.containsKey("status")) {
            if (!"".equals(map.get("status")) && Integer.parseInt(map.get("status").toString()) == 0) {
                map.put("status", 1);
                map.put("_status", 2);
            }
        }
        PageInfo<List<Requester>> data = requesterService.searchByCondition(map);
        List<Requester> requesterList = data.getList();
        /*List<Stream<String>> userIds = Stream.of(
//                requesterList.stream().map(Requester::getCreateById),
                requesterList.stream().map(Requester::getModifiedById)
        ).distinct().collect(Collectors.toList());*/
        List<String> userIdList = requesterList.stream().map(Requester::getModifiedById).distinct().collect(Collectors.toList());
        if (userIdList.size() > 0) {
            /*Map<String, Object> usermap = Maps.newHashMap();
            usermap.put("userIdList", userIdList);
            usermap.put("pageSize", userIdList.size());*/
            AllCondition condition = new AllCondition();
            condition.setPageSize(userIdList.size());
            condition.setPageNum(1);//默认0 分页算法报错
            condition.setUserIdList(userIdList);
//            Result<PageInfo<User>> userResult = userServiceClient.list(usermap);
            Result<PageInfo<User>> userResult = userServiceClient.list(JSON.parseObject(JSON.toJSONString(condition), Maps.newHashMap().getClass()));
            List<User> userList = JSON.parseArray(JSON.toJSONString(userResult.getData().getList()), User.class);
            List<RequesterVo> voList = requesterList.stream().map(r -> {
                RequesterVo vo = new RequesterVo();
                BeanUtils.copyProperties(r, vo);
                userList.stream().filter(u -> u.getUserId().equalsIgnoreCase(r.getModifiedById())).findAny().ifPresent(u -> vo.setLastUpdateByName(u.getName()));
                return vo;
            }).collect(Collectors.toList());
            data.setList(voList);
        }
        return data;
    }

    /**
     * 查询全部
     *
     * @param
     * @return
     */
    @OperationLogAnnotation(operateName = "查询全部请求方列表", operateType = OperateType.SELECT, module = "requester")
    @RequestMapping(method = RequestMethod.GET)
    public Object list() throws Exception {
        return requesterService.list(null);
    }

    /**
     * 通过ID查找对象
     *
     * @param id
     * @return
     */
    @OperationLogAnnotation(operateName = "通过ID查找对象请求方", operateType = OperateType.SELECT, module = "requester")
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Object detail(@PathVariable Integer id) throws Exception {
        return requesterService.getById(id);
    }

    /**
     * 创建
     *
     * @param requester
     * @return
     */
    @OperationLogAnnotation(operateName = "创建请求方", operateType = OperateType.INSERT, module = "requester")
    @RequestMapping(method = RequestMethod.POST)
    public Object create(@RequestBody Requester requester) throws Exception {
        Result<User> result = userServiceClient.getCurrentUserInfo();
        requester.setCreateById(result.getData().getUserId());
        requester.setCreateByName(result.getData().getName());
        return requesterService.save(requester);
    }

    /**
     * 更新
     *
     * @param requester
     * @return
     */
    @OperationLogAnnotation(operateName = "更新请求方", operateType = OperateType.UPDATE, module = "requester")
    @RequestMapping(method = RequestMethod.PUT)
    public Object update(@RequestBody Requester requester) throws Exception {
        Result<User> result = userServiceClient.getCurrentUserInfo();
        requester.setModifiedById(result.getData().getUserId());
        return requesterService.update(requester);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @OperationLogAnnotation(operateName = "删除请求方", operateType = OperateType.DELETE, module = "requester")
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Object delete(@PathVariable Integer id) throws Exception {
        return requesterService.deleteById(id);
    }

    /**
     * 审核
     *
     * @param map
     * @return java.lang.Object
     * @author Mr.Lin
     * @date 2018/3/9 15:51
     */
    @ApiOperation(value = "审核", notes = "", response = Integer.class)
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id", value = "id", required = true, dataType = "int")
            , @ApiImplicitParam(name = "status", value = "审核状态：1:注册未审核，2:变更未审核，3:审核通过，4:审核不通过", required = true, dataType = "int")
    })
    @OperationLogAnnotation(operateName = "请求方审核", operateType = OperateType.UPDATE, module = "requester")
    @RequestMapping(value = "/check", method = RequestMethod.POST)
    public Object check(@RequestBody Map<String, Object> map) throws Exception {
        Result<User> currUser = userServiceClient.getCurrentUserInfo();
        map.put("userId", currUser.getData().getUserId());
        return requesterService.check(map);
    }

    /**
     * 带条件统计请求方数量
     *
     * @param map
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "带条件统计请求方数量", notes = "", response = ProviderVO.class)
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "startTime", value = "注册开始时间", required = true, dataType = "Date")
            , @ApiImplicitParam(name = "endTime", value = "注册结束时间", required = true, dataType = "Date")

    })
    @OperationLogAnnotation(operateName = "带条件统计请求方数量", operateType = OperateType.SELECT, module = "requester")
    @RequestMapping(value = "/countByCondition", method = RequestMethod.POST)
    public Object countByCondition(@RequestBody Map<String, Object> map) throws Exception {
        Object data = requesterService.countByCondition(map);
        return data;
    }

    /**
     * 通过organization统计
     *
     * @param map
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/requesterCountByOrganization", method = RequestMethod.POST)
    public Object requesterCountByOrganization(@RequestBody Map<String, Object> map) throws Exception {
        Object data = requesterService.requesterCountByOrganization(map);
        return data;
    }

    @RequestMapping(value = "/seachUserByCurrent", method = RequestMethod.POST)
    public Object seachUser(@RequestBody Map<String, Object> map) throws Exception {
        List list = new ArrayList();
        if (!"".equals(map.get("roleId")) && Integer.parseInt(map.get("roleId").toString()) == 0) {
            map.put("orgSerialNo", userServiceClient.getCurrentUserInfo().getData().getUserId());
            Result<PageInfo<User>> result = userServiceClient.list(map);
            list = result.getData().getList();
        } else {
            Result<User> user = userServiceClient.getCurrentUserInfo();
            list.add(user.getData());
        }
        return list;
    }

    /**
     * 每月请求数总量
     *
     * @param map
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/monthlyRequesterCount", method = RequestMethod.POST)
    public Object monthlyRequesterCount(@RequestBody Map<String, Object> map) throws Exception {
        PageInfo data = (PageInfo) requesterService.monthlyRequesterCount(map);
        List<MonthlyRequesterCountVo> month_data = (List<MonthlyRequesterCountVo>) data.getList();

        //获取前6个月日期
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Date date = new Date();
        String dateString = sdf.format(cal.getTime());
        List<String> rqList = new ArrayList<>();
        for (int i = 0; i < 12; i++) {
            dateString = sdf.format(cal.getTime());
            rqList.add(dateString.substring(0, 7));
            cal.add(Calendar.MONTH, -1);
        }
        Collections.sort(rqList);

        //日期数数组
        String[] rqArr = new String[rqList.size()];
        //网络1/移动信息网数组
        int[] ydxxwArr = new int[rqList.size()];
        //网络2/公安内网数组
        int[] ganwArr = new int[rqList.size()];
        //其它网络数组
        int[] qtwArr = new int[rqList.size()];
        //初始化数组，设置默认值
        for (int i = 0; i < rqList.size(); i++) {
            ydxxwArr[i] = 0;
            ganwArr[i] = 0;
            qtwArr[i] = 0;
        }

        for (int i = 0; i < rqList.size(); i++) {
            for (int j = 0; j < month_data.size(); j++) {
                String rq = rqList.get(i).toString();
                MonthlyRequesterCountVo vo = month_data.get(j);
                if (rq.equals(vo.getRq())) {
                    if (vo.getRequester() == 1) {
                        ydxxwArr[i] = vo.getCount();
                    } else if (vo.getRequester() == 2) {
                        ganwArr[i] = vo.getCount();
                    } else {
                        qtwArr[i] = vo.getCount();
                    }
                }
            }
            rqArr[i] = rqList.get(i).toString();
        }
        List resultList = new ArrayList();
        Map<String, Object> maps = new HashMap<String, Object>();
        maps.put("rqArr", rqArr);
        maps.put("ydxxwArr", ydxxwArr);
        maps.put("ganwArr", ganwArr);
        maps.put("qtwArr", qtwArr);
        resultList.add(maps);
        Result result = new Result();
        result.setData(resultList);
        return result;
    }
}
